
var Moossenger = Windoo.extend({

    initialize: function(id, user, dest, options){
        this.parent(options); //will call initalize of Windoo
        this.user = user;
        this.recipient = dest;
        this.id = id;
        
        this.toolbar = new Toolbar (this.id, {toolbar:false, fontbar:false, emoticon:false});
    },
    
    getUsername: function () {
    	return this.user.getName();
    },
    
    getUserId: function () {
    	return this.user.getId();
    },
    
    getRecipientName: function() {
    	return this.recipient.getName();
    },
    
    getRecipientId: function() {
    	return this.recipient.getId();
    },
       
	sendResult: function(objMess, result) {
	      var dialogBox = $(this.getId()+dialogSuffix);
	     
	      if(result != null) {
	         dialogBox.innerHTML = dialogBox.innerHTML + '<span class="imError">' + result + '</span><br>';
	      }
	      
		  var message = objMess.content;
	      if(trim(message).length > 0) {
	         message = this.emoteReplace(message, emoticons);
	         if(message.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0)
	            dialogBox.innerHTML = dialogBox.innerHTML + "<b class=\"userA\">" + createTimestamp() + " <i>" + this.getUsername() + ' ' + message.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
	         else {
	            dialogBox.innerHTML = dialogBox.innerHTML + "<b class=\"userA\">" + createTimestamp() + " " + objMess.getSenderName() + ":</b> " + message + "<br>\n";
	         }
	      }
	
	      scrollToBottom(this.getId()+dialogSuffix);
	},


 	/**
    * Checks to see if there is a message, if there is,
    * send it to the server.
    *
    * @author Joshua Gross
    * @update Benjamin Hitchins
    **/
   send: function() {
      var sendBox = $(this.getId()+inputSuffix);

      var isBold      = (sendBox.style.fontWeight == '400' ? 'false' : 'true');
      var isItalic    = (sendBox.style.fontStyle == 'normal' ? 'false' : 'true');
      var isUnderline = (sendBox.style.textDecoration == 'none' ? 'false' : 'true');
      var fontName    = 'Arial'; //$(this.getId()+'_setFont').innerHTML;
      var fontSize    = '12'; //$(this.getId()+'_setFontSize').innerHTML;
      var fontColor   = 'black'; //$(this.getId()+'_setFontColorColor').style.backgroundColor;

      if(trim(sendBox.value).length > 0) {
         var message = sendBox.value;
         sendBox.value = '';
         message = message.replace(/&/g, "&amp;").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, "<br/>");
         
         var objMsg = new Message (this.user, this.recipient, message,
                                   {bold:isBold, italic:isItalic, underline:isUnderline, 
                                    fontName:fontName, fontSize: fontSize, 
                                    fontColor: fontColor, type: 'msg'});
                                    
         this.sendMessage(objMsg);
      }

      scrollToBottom(this.getId()+dialogSuffix);
      sendBox.focus();
   },
   
   /**
    * Checks for pressing on 'Return' or 'Enter'
    *
    * @author Joshua Gross
    * @update Benjamin Hutchins
    * @update G. henson
    **/
   keyHandler: function(event) {
      event = event || window.event;
      var asc = document.all ? event.keyCode : event.which;
      var shift = event.shiftKey;
      
      if(asc == 13 && !shift) {
         this.send();
         return false;
      }

      return true;
   },
   
   /**
    * Detaches an IM window to a new window
    *
    * @author Joshua Gross
    * @update Benjamin Hutchins
    **/
   detach: function() {
      newWin = this.getUserName();
      newWinDialog = $(this.getId()+dialogSuffix).innerHTML;
      this.hide();
      this.popup = window.open('./popup.html', winId + '_im', 'left='+this.getLocation()['left']+',top='+this.getLocation()['top']+',width=320,height=335,toolbar=0,location=1,status=0,menubar=0,resizable=1,scrollbars=0');
      this.detached = true;
   },
   
   /**
    * Sends a message to the server
    *
    * @arguments
    *   username - who the message is being sent to
    *   message - the message to send
    *   chatroom - (bool) is this a chatroom
    *   isBold - (bool) is the message bolded
    *   isItalic - (bool) is the message italicized
    *   isUnderline - (bool) is the message underlined
    *   fontName - font family for the message
    *   fontSize - font size for the message
    *   fontColor - font color for the message
    *
    * @author g henson
    **/
   sendMessage: function(message) {  
      var myXhr = new XHR({	method: 'post', 
      						onSuccess: function() {
							            var error = null;
										
							            switch(this.response['text']) {
							               case 'sent':
							                  // do nothing
							               break;
							
							               case 'sent_offline':
							                  error = Languages.get('notifySentButOffline');
							                  //error = 'notifySentButOffline';
							               break;
							
							               case 'not_online':
							                  error = Languages.get('errorNotLoggedIn');
							                  //error = 'errorNotLoggedIn';
							               break;
							
							               case 'too_long':
							                  error = Languages.get('errorMsgTooLong');
							                  //error = 'errorMsgTooLong';
							               break;
							
							               case 'not_logged_in':
							                  if (typeof System != 'undefined') {
							                     System.logout();
							                  } else {
							                     self.opener.System.logout();
							                  }
							               break;
							
							               default:
							                  error = Languages.get('errorUnknown');
							                  //error = 'errorUnknown';
							               break;
							            }
										
										message.format();																           							
							            imManager.windows[message.getRecipientId()].sendResult(message, error);
							            
							         }}).send(urlToPing, "action=send&caller="+this.getUserId()+"&recipient="+message.getRecipientId()+"&bold="+message.options.bold+"&italic="+message.options.italic+"&underline="+message.options.italic+"&font="+message.options.fontName+"&fontsize="+message.options.fontSize+"&fontcolor="+message.options.fontColor+"&message="+encodeURIComponent(message.content));
		
      if(audioNotify == true) {
      	var ret = soundManager.play('msg_out');
      }
					
   },
   
   getId: function () {
   		return this.id;
   },
   
   getToolbar: function () {
   		return this.toolbar;
   },
   
   /**
    * Adds text to a windows' message box
    *
    * @author Joshua Gross
    * @update g henson
    **/
   insertText: function(tti) {
      var winId = this.getId();
      var sendBox = $(winId + inputSuffix);
      
      sendBox.value += tti;
      //setTimeout("$('" + winId + "_sendBox').focus();", 125);
      this.getToolbar().toggleEmoticonList();
      return false;
   },
   
   /**
    * Replaces emotes with images
    *
    * @arguments
    *   str - the message to run replaces on
    *   itemsList - array of emotes
    **/
   emoteReplace: function(str, itemsList) {
      var r;
      for(var s in itemsList) {
         if(str.indexOf(s) > -1)
            str = str.replace(new RegExp(regExpEscape(s), 'g'), '<img src="'+ pathTous +'themes/' + theme + '/emoticons/' + itemsList[s] + '" alt="' + itemsList[s] + '" title="' + s + '" />');
      }
      return str;
   },
   
   resizeDialogBox: function () {
   		var dialogBox = $(this.getId()+dialogSuffix);
   		if (dialogBox) {
   			// winheight is the window inner height
   			var winheigh = this.getState()['inner']['size']['y'];
   			// the table is 98% of the window (defined in the css)
   			// the bottom of the window (the capture area) is 70 px (defined in the css)
   			// the separator is 2px
   			// the borders are 2px (top + bottom)
	   		var hg = (100/100) * (((98/100) * winheigh) - 74);	
	   		dialogBox.setStyle ('height', hg);
	   	}		
   },
   
   /**
    * send an event to notify the recipient the user has closed his conversation with him
    * 
    * @author g henson
    */
   sendCloseEvent: function () {
   		var myXhr = new XHR({	method: 'post', 
   								headers: {'sender':this.getUsername(), 'recipient' : this.getRecipientId(), 'content' : $(this.getId()+dialogSuffix).innerHTML},
      							onSuccess: function() {
      									System.store(this.headers['sender'], this.headers['recipient'], this.headers['content']);
							           /* switch(this.response['text']) {		               
							               case 'not_online':
							               	  // recipient is logged out
							               	  // store the conversation
							               	  System.store(this.userid, this.toid);
							               break;
							               
							               default :
							               		// do nothing
							               break;
							            }*/
							         }}).send(urlToPing, "action=sendevent&caller="+this.getUserId()+"&recipient="+this.getRecipientId()+"&event=close");		
   },
   
   /**
    * notify the window of a new message
    * @author g henson 
    */
   notify: function () {
   
   	  if(audioNotify == true) soundManager.play('msg_in');

   	  // if the window is not focused or is minimized
   	  if (!(Windoo.$wm.focused === this) || this.minimized) {
   	  	  // the background of the window title is painted in red.
	   	  var topwin = $(this.options.id).getElements('div').filterByClass('title');
	   	  //topwin.setStyle('background', 'red url(themes/windoo/windoo.alphacube/north-red.gif) repeat-x scroll 0pt -44px');
	   	  topwin.setStyle('background', 'red repeat-x scroll 0pt -44px'); 
	  }
	  else {
	  	  // the background of the window title is changed back to normal
	   	  var topwin = $(this.options.id).getElements('div').filterByClass('title');
	   	  topwin.removeProperty('Style');   	  
	  }
   },
   
   /**
    * restore the current window :
    * if it's minized, restore to its size
    * then bring it to top and gives it focus
    * @author : g henson
   */
   restore: function () {
   		if (this.minimized) {
   			this.minimize();
   		}
   		return this.bringTop().focus();
   }
   
});
   